//
//  YXReleaseViewController.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/27.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXReleaseViewController.h"
#import "YXReleaseHeaderView.h"
#import "YXReleaseContentView.h"
#import "YXReleaseAleatView.h"
#import "UIImage+YXVideo.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>

@interface YXReleaseViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic ,strong) UIScrollView *scrollView;
@property (nonatomic ,strong) YXReleaseHeaderView *headerView;
@property (nonatomic ,strong) YXReleaseContentView *contentView;
@property (nonatomic ,strong) UIButton *addBtn;
@property (nonatomic ,assign) NSInteger number;
@property (nonatomic ,strong) UIButton *videoBtn;
@property (nonatomic ,assign) CGFloat scrollerViewHeight;
@end

@implementation YXReleaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = color_backColor;
    [self createLeftBarButtonItemWithImage:@"导航栏_002"];
    self.title = @"发布";
    [self createNarBarUI];
    [self createUI];
}

- (void)createNarBarUI {
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightItemAction)];
    rightItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)rightItemAction {

    if (self.typeView == Release_Graphic) {
        
        if (self.headerView.titleView.text.length == 0 || self.contentView.contentView.text.length == 0) {
            [self showTostMessage:@"发布标题、内容必填！"];
        }else {
            //http://121.196.210.134:8082/mpos/wx/addPost.do?title=今天的post机器好用吗&contents=内容第一内日内容第一哦&type=0&sessionId=93e2c13a-f0a1-47ba-a30c-7225ee06b64d
            NSString *str = [[NSString stringWithFormat:@"addPost.do?sessionId=%@&title=%@&contents=%@&type=%@", [YXUserInfoManager getUserInfo].sessionId, self.headerView.titleView.text, self.contentView.contentView.text, @"2"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [BX_NetWorkManager requestForGETWithUrl:str parameter:nil success:^(id responseObject) {
                NSLog(@"%@",responseObject);
                if (REQUESTDATASUCCESS) {
                    YXReleaseAleatView *aleatView = [[YXReleaseAleatView alloc] initWithFrame:[UIScreen mainScreen].bounds];
                    [aleatView showCustomAlertView];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [self showAlertWithTitle:@"提示" Messge:@"维护中，请稍等！"];
                
            }];
        }
            
    }else {
        
        
    }

}

- (void)createUI {
    
    
    switch (self.typeView) {
        case Release_Graphic:
        {
            self.scrollView = [[UIScrollView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, kScreenHeight))];
            self.scrollView.backgroundColor = color_backColor;
            self.scrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight * 1);
            [self.view addSubview:self.scrollView];
            
            self.headerView = [[YXReleaseHeaderView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 200))];
            [self.scrollView addSubview:self.headerView];
            
            UIView *titleView = [self createTitleView];
            titleView.frame = CGRectMake(0, self.headerView.Y + self.headerView.H-64, kScreenWidth, 30);
            [self.scrollView addSubview:titleView];
            
            self.number = 1;
            _contentView = [[YXReleaseContentView alloc] initWithFrame:(CGRectMake(0, titleView.H + titleView.Y, kScreenWidth, 200))];
            [self.scrollView addSubview:self.contentView];
            
            // 获取图片
            [_contentView.imgPicker observeSelectedMediaArray:^(NSArray<LLImagePickerModel *> *list) {
                for (LLImagePickerModel *model in list) {
                    NSLog(@"%@",model.image);
                }
            }];
            
            self.addBtn = [self createButton];
            self.addBtn.frame = CGRectMake(20, _contentView.H + _contentView.Y + 10, kScreenWidth - 40, 50);
            [self.scrollView addSubview:self.addBtn];

        }
            break;
        case Release_Video:
        {
            self.headerView = [[YXReleaseHeaderView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, 200))];
            [self.view addSubview:self.headerView];
            
            UIView *titleView = [self createTitleView];
            titleView.frame = CGRectMake(0, self.headerView.Y + self.headerView.H-64, kScreenWidth, 30);
            [self.view addSubview:titleView];
            
            _contentView = [[YXReleaseContentView alloc] initWithFrame:(CGRectMake(0, titleView.H + titleView.Y, kScreenWidth, 250))];
            [self.view addSubview:self.contentView];
            
            UIButton *addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
            addBtn.frame = CGRectMake(10, _contentView.H + _contentView.Y + 10 -64, 50, 50);
            [addBtn setImage:[UIImage imageNamed:@"添加视频"] forState:(UIControlStateNormal)];
            [addBtn addTarget:self action:@selector(addBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [self.view addSubview:addBtn];
            
            UIButton *videoBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
            videoBtn.frame = CGRectMake(70, _contentView.H + _contentView.Y + 10 -64, 50, 50);
            [videoBtn addTarget:self action:@selector(videoBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [self.view addSubview:videoBtn];
            _videoBtn = videoBtn;
        

        }
            break;
        default:
            break;
    }
}

-(UIView *)createTitleView {
    
    UIView *titleView = [[UIView alloc] init];
    titleView.backgroundColor = color_backColor;
    
    UIView *lineView = [[UIView alloc] initWithFrame:(CGRectMake(10, 6, 3, 18))];
    lineView.backgroundColor = color_blueColor;
    [titleView addSubview:lineView];
    
    UILabel *titleLab = [UILabel setLabelWithText:@"段落列表" fontSize:18 color:color_textTwo];
    titleLab.frame = CGRectMake(20, 5, 100, 20);
    [titleView addSubview:titleLab];
    
    return titleView;
}

- (UIButton *)createButton {
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button setBackgroundColor:color_globalColor];
    [button setTitle:@"新增段落" forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    button.layer.cornerRadius = 8.0f;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(action:) forControlEvents:(UIControlEventTouchUpInside)];
    return button;
}

- (void)action:(UIButton *)sender {
    /*
    self.number ++ ;
    NSLog(@"%ld",self.number);
    if (self.number == 2) {
        YXReleaseContentView *contentView1 = [[YXReleaseContentView alloc] initWithFrame:(CGRectMake(0, _contentView.H + _contentView.Y + 10, kScreenWidth, 200))];
        [self.scrollView addSubview:contentView1];
        CGRect rect = sender.frame;
        rect.origin.y += 210;
        sender.frame = rect;
    }else if (self.number == 3){
        YXReleaseContentView *contentView2 = [[YXReleaseContentView alloc] initWithFrame:(CGRectMake(0, _contentView.H + _contentView.Y + 10 + 210, kScreenWidth, 200))];
        [self.scrollView addSubview:contentView2];
        CGRect rect = sender.frame;
        rect.origin.y += 210;
        sender.frame = rect;
    }else if (self.number > 3) {
        [self showTostMessage:@"段落已最大，不能添加！"];
    }
     */
   


    CGFloat maxY = _contentView.H + _contentView.Y + 10;
    CGRect rect1 = _contentView.frame;
    rect1.origin.y += maxY;
    [self addContentView:maxY];
    
    CGRect rect = sender.frame;
    rect.origin.y += 210;
    sender.frame = rect;
    
    self.scrollerViewHeight += 210;
    [self addScrollViewHeight:self.scrollerViewHeight];
}

- (void)addScrollViewHeight:(CGFloat)height {
    self.scrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight + height);
}


- (void)addContentView:(CGFloat)maxY {
    _contentView = [[YXReleaseContentView alloc] initWithFrame:(CGRectMake(0, maxY, kScreenWidth, 200))];
    [self.scrollView addSubview:_contentView];
}


- (void)addBtnAction:(UIButton *)sender {
    
    NSLog(@"从相册选择");
    UIImagePickerController *picker=[[UIImagePickerController alloc] init];
    
    picker.delegate=self;
    picker.allowsEditing=NO;
    picker.videoMaximumDuration = 1.0;//视频最长长度
    picker.videoQuality = UIImagePickerControllerQualityTypeMedium;//视频质量
    
    //媒体类型：@"public.movie" 为视频  @"public.image" 为图片
    //这里只选择展示视频
    picker.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil, nil];
    
    picker.sourceType= UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:@"public.movie"]){
        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];//获得视频的URL
        NSLog(@"url %@",url);
//        self.videoUrl = url;
        //获取视频的thumbnail
        UIImage *image = [UIImage imageWithVideo:url];
        [self.videoBtn setImage:[UIImage imageNamed:@"椭圆4"] forState:(UIControlStateNormal)];
        [self.videoBtn setBackgroundImage:image forState:(UIControlStateNormal)];
        
        
        NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:url]]);
        NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[url path]]]);
        NSURL *newVideoUrl; //一般.mp4
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
         [self convertVideoQuailtyWithInputURL:url outputURL:newVideoUrl completeHandler:nil];
    }
   

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                               outputURL:(NSURL*)outputURL
                         completeHandler:(void (^)(AVAssetExportSession*))handler
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    //  NSLog(resultPath);
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
                 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
                 
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                 
//                 [self alertUploadVideo:outputURL];
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
         
     }];
    
}

//清除documents中视频
-(void)ClearMovieFromDoucments{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        NSLog(@"%@",filename);
        if ([filename isEqualToString:@"tmp.PNG"]) {
            NSLog(@"删除%@",filename);
            [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
            continue;
        }
        if ([[[filename pathExtension] lowercaseString] isEqualToString:@"mp4"]||
            [[[filename pathExtension] lowercaseString] isEqualToString:@"mov"]||
            [[[filename pathExtension] lowercaseString] isEqualToString:@"png"]) {
            NSLog(@"删除%@",filename);
            [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        }
    }
}

- (void)videoBtnAction:(UIButton *)sender {
    
    
}

- (CGFloat) getFileSize:(NSString *)path
{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}//此方法可以获取视频文件的时长。


@end
